iT邦幫忙

2024 iThome 鐵人賽

DAY 6
0

關於請求參數取得對於開發 API 或是運行任何服務來說是相當重要,特別是我們需要根據使用者請求中所帶有的資訊進行後續的處理,所以這篇就來了解 Spring MVC 中主要用來取得參數的一些方法吧。

Spring Boot 常使用取得請求的方式有下面這些:

  • @RequestParam
  • @RequestBody
  • @PathVariable
  • @RequestHeader

@RequestParam

用法:

  • GET
  • required = true/false (預設 true),如果是 false 就不用代入但可能會因此有 null 報 exception
  • defaultValue = xxx,設置預設值,設置後 required 就會被忽略

用途:取得放在 URL 的參數

http:localhost:8080/test1?id=123

@RestController
public class RequestController {
    @RequestMapping("/test1")
    public String test1(@RequestParam Integer id,
                        @RequestParam(defaultValue = "Sean") String name,
                        @RequestParam(value = "nickname", required = false) String nickname
    ) {
        System.out.println("id:" + id);
        System.out.println("name:" + name);
        System.out.println("name:" + nickname);
        return "your request id is " + id + " and name is " + name + ", or you can called me " + nickname;
    }
}

發送 request,帶入 id =1, name = Sean,故意不帶入第3個參數 nickname,可以看到最後會回傳 null 但也不會出錯誤,但如果把 required = true 就會出現 400 Bad Request 錯誤。
https://ithelp.ithome.com.tw/upload/images/20240828/20150977Y3trp9BV9C.png

server console 上面顯示
https://ithelp.ithome.com.tw/upload/images/20240828/20150977AodpypyvLC.png

@RequestBody

用法:

  • POST, PUT
  • required = true/false (預設 true)
  • 需要先定義對應參數的 java class
  • RequestBody 裡面多傳參數也不會報錯,有定義的才會被使用,少傳就會有 null

用途:取得 Request body 裡面的參數(將 Json 轉為自定義 Java Object)

http:localhost:8080/test2

controller

@RequestMapping("/test2")
public String test2(@RequestBody Student student){
    System.out.println("student id: " + student.getId() );
    System.out.println("student name: " + student.getName() );
    return "hello test2";
}

Student class

public class Student {
    Integer id;
    String name;
    
    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
}

發送 request,帶入{ “id” =1, “name” = “Sean” }的 JSON 物件,如果請求內所帶的物件屬性不是Student 物件設定的,不管多或少其實都不會有問題,但如果希望參數設定可以驗證避免使用者傳錯參數的話,就必須要透過驗證註解像是@Valid, @NotNull, @NotBlank 等等的部分才可以做到了,這部分後續文章會有進一步說明。

https://ithelp.ithome.com.tw/upload/images/20240828/20150977J6csZFkKm2.png
https://ithelp.ithome.com.tw/upload/images/20240828/20150977JhavXUBYiK.png

server console 上面顯示

https://ithelp.ithome.com.tw/upload/images/20240828/20150977Y0ibiGA9vV.png

@RequestHeader

用法:

  • GET, POST
  • 只能加在方法參數上
  • name(或用 value): 指定 request header 的 header 名字(比 requestparam 的 name 常用)
  • required = true/false 同 @RequestParam
  • defaultValue: 預設值 同 @RequestParam

用途:取得放在 requestHeader 的參數,可以用 GET 請求中設定 header; 如果用 POST 一般都會帶入 Content-Type = application/json

@RequestMapping("/test3")
public String test3(@RequestHeader String info,
                    @RequestHeader (name = "gogo", required = false) String gogo){
    System.out.println("header info: " + info);
    System.out.println("header gogo: " + gogo);
    return "hello test3";
}

發送 request,header上面帶入指定的 header 名稱,如果是參數定義的就可以抓到
https://ithelp.ithome.com.tw/upload/images/20240828/20150977h3Fc2FWnQ1.png

console 上面顯示
https://ithelp.ithome.com.tw/upload/images/20240828/20150977T3ld4FmqGn.png

@PathVariable

用法:

  • GET, PUT, DELETE
  • 路徑上寫的參數要和 @PathVariable 定義的一樣用途:取得放在 URL 路徑裡面的值
  • required = true/false (預設 true),如果是 false 就不用代入但可能會因此有 null 報 exception

http://localhost:8080/test4/123/Sean

@RequestMapping("/test4/{id}/{name}")
    public String test4(@PathVariable Integer id,
                        @PathVariable String name
    ){
        System.out.println("path id: " + id);
        System.out.println("path name: " + name);
        return "hello test4";
    }

發送 request,URL 上針對 {id}, {name} 部分帶入參數,後端就可以取得,注意定義的參數類型如果不匹配也會出現 400 bad request,像是如果你把 id 部分用文字帶入請求。
https://ithelp.ithome.com.tw/upload/images/20240828/20150977YlcOJ9OrMM.png

console 上面顯示
https://ithelp.ithome.com.tw/upload/images/20240828/20150977InAcovAfLY.png


小總結:

針對一些用法上大家可以注意一下

Http method required defaultValue 常用情境
@RequestParam GET O (預設true) O 查詢參數或表單數據
@RequestBody POST, PUT O (預設true) X 處理 JSON 或 XML 請求
@PathVariable GET, PUT, DELETE O (預設true) X URL 路徑中的變數
@RequestHeader GETPOST O (預設true) O 獲取 HTTP 請求header

參考資料:

  1. Java 工程師必備!Spring Boot 零基礎入門 (hahow 課程)


上一篇
Day 5 - Spring MVC (1) - 基本介紹
下一篇
Day 7 - Spring MVC (3) - Thymeleaf
系列文
關於我和 Spring Boot 變成家人的那件事15
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言